package org.iks.push.config;

import lombok.extern.slf4j.Slf4j;
import org.iks.push.business.vo.OnlineUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Author kzou
 * Date 2024/2/12
 * Description:
 */
@Slf4j
@Component
public class RedisCacheUtil {

    private static final String OnlineUserKey = "onlineUser";
    private static RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheUtil.redisTemplate = redisTemplate;
    }

    public static void storeUser(OnlineUserVo vo) {
        log.info("store online user: {}", vo);
        redisTemplate.opsForHash().put(OnlineUserKey, vo.account, vo);
    }

    public static OnlineUserVo queryUser(String account) {
        return (OnlineUserVo) redisTemplate.opsForHash().get(OnlineUserKey, account);
    }

    public static void deleteUser(String account) {
        redisTemplate.opsForHash().delete(OnlineUserKey, account);
    }

    public static List<OnlineUserVo> queryAll() {
        Set<Object> keys = redisTemplate.opsForHash().keys(OnlineUserKey);
        return keys.stream().map(it -> queryUser((String) it)).collect(Collectors.toList());
    }

}
